<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <label for="imgg">选择图片</label>
    <input type="file" class="img" id="imgg" style="display: none;">

    <script>

        document.querySelector('.img').addEventListener('change', function () {

            // 1. 获取选择的图片
            let file = this.files[0]

            // 2. 实例化FormData对象
            const fd = new FormData()
            fd.append('avatar', file)
            fd.append('creator', 'xiaobai')

            const xhr = new XMLHttpRequest()
            xhr.open('PUT', 'https://hmajax.itheima.net/api/avatar')
            xhr.addEventListener('loadend', function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log(xhr.response)
                } else {
                    alert('失败')
                }
            })

            // 3. 将formData对象提交给服务器
            xhr.send(fd)
        })


    </script>
</body>

</html>